<?php

namespace Houdunwang\WeChat;

use Houdunwang\WeChat\Type\MessageType;
use Illuminate\Support\Facades\Log;

/**微信包
 * Class WeChat
 * @package Houdunwang\WeChat
 */
class WeChat extends MessageType
{
    //配置项
    protected static $config;

    protected static $message;

    public function __get($name)
    {
        return self::$message->$name ?? '';
    }

    public function init($config)
    {
        $this->config($config)->bind();
        $this->message();
    }


    /**
     * 识别粉丝发送的消息
     */
    protected function message()
    {
        $content = file_get_contents('php://input');
        if ($content) {
            //接收到的数据给到$message
            self::$message = @simplexml_load_string($content);
        }
    }

    /**
     *设置或者获取配置项
     * @param $config
     * @return $this|null
     *
     */
    protected function config($config = null)
    {
        //批量设置
        if (is_string($config)) {
            return self::$config[$config] ?? null;
            //获取全部
        } elseif (is_null($config)) {
            return self::$config;
        }
        self::$config = $config;
        return $this;
    }

    /**
     * 绑定公众号
     * @return bool
     */
    public function bind()
    {
        if (isset($_GET["signature"]) && isset($_GET["timestamp"]) && isset($_GET['echostr'])) {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];

            $token = $this->config('token');
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);

            if ($tmpStr == $signature) {
                die($_GET['echostr']);
            }
        }
//        return true;
    }

    public function token()
    {

    }


}
